package org.com.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.com.pojo.ProductImages;
import org.com.pojo.Products;
import org.com.pojo.Farms;
import org.com.pojo.ProductCategories;
import org.com.pojo.FarmsImages;
import org.com.mapper.ProductImagesMapper;
import org.com.mapper.ProductsMapper;
import org.com.mapper.FarmsMapper;
import org.com.mapper.ProductCategoriesMapper;
import org.com.mapper.FarmsImagesMapper;
import org.com.service.ProductsService;
import org.com.util.AliOssUtil;
import org.com.common.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.HashMap;
import java.util.stream.Collectors;
import java.util.Date;

/**
* @author 86134
* @description 针对表【products】的数据库操作Service实现
* @createDate 2025-02-27 16:33:36
*/
@Slf4j
@Service
public class ProductsServiceImpl extends ServiceImpl<ProductsMapper, Products>
    implements ProductsService{

    @Autowired
    private ProductImagesMapper productImagesMapper;

    @Autowired
    private FarmsMapper farmsMapper;

    @Autowired
    private AliOssUtil aliOssUtil;

    @Autowired
    private ProductCategoriesMapper productCategoriesMapper;

    @Autowired
    private FarmsImagesMapper farmsImagesMapper;
    
    @Override
    public R getFarmProducts(Integer farmId) {
        try {
            if (farmId == null) {
                return R.error("农场ID不能为空");
            }
            
            // 获取农场所有商品
            LambdaQueryWrapper<Products> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Products::getFarmId, farmId);
            List<Products> products = this.list(queryWrapper);
            
            if (products.isEmpty()) {
                return R.success("暂无商品数据", new ArrayList<>());
            }
            
            // 获取所有商品的图片
            List<ProductImages> allImages = productImagesMapper.getImagesByFarmId(farmId);
            
            // 获取所有商品的分类信息
            List<Map<String, Object>> categories = productImagesMapper.getProductCategoriesByFarmId(farmId);
            
            // 按商品ID分组图片
            Map<Integer, List<ProductImages>> imageMap = allImages.stream()
                .collect(Collectors.groupingBy(ProductImages::getProductId));
            
            // 按商品ID分组分类信息
            Map<Integer, List<Map<String, Object>>> categoryMap = categories.stream()
                .collect(Collectors.groupingBy(item -> (Integer)item.get("product_id")));
            
            // 构建返回数据
            List<Map<String, Object>> resultList = products.stream().map(product -> {
                Map<String, Object> productMap = new HashMap<>();
                productMap.put("product", product);
                productMap.put("images", imageMap.getOrDefault(product.getProductId(), new ArrayList<>()));
                productMap.put("categories", categoryMap.getOrDefault(product.getProductId(), new ArrayList<>()));
                return productMap;
            }).collect(Collectors.toList());
            
            return R.success("获取商品列表成功", resultList);
        } catch (Exception e) {
            log.error("获取农场商品列表失败", e);
            return R.error("获取农场商品列表失败：" + e.getMessage());
        }
    }
    
    @Override
    public R getUserProducts(Integer userId) {
        try {
            if (userId == null) {
                return R.error("用户ID不能为空");
            }
            
            // 获取用户的所有农场
            LambdaQueryWrapper<Farms> farmQuery = new LambdaQueryWrapper<>();
            farmQuery.eq(Farms::getUserId, userId);
            List<Farms> userFarms = farmsMapper.selectList(farmQuery);
            
            if (userFarms.isEmpty()) {
                return R.success("暂无农场数据", new ArrayList<>());
            }
            
            // 获取所有农场的商品
            List<Map<String, Object>> allProducts = new ArrayList<>();
            for (Farms farm : userFarms) {
                // 获取农场的所有商品
                LambdaQueryWrapper<Products> productQuery = new LambdaQueryWrapper<>();
                productQuery.eq(Products::getFarmId, farm.getFarmId());
                List<Products> farmProducts = this.list(productQuery);
                
                if (!farmProducts.isEmpty()) {
                    // 获取所有商品的图片
                    List<ProductImages> productImages = productImagesMapper.getImagesByFarmId(farm.getFarmId());
                    
                    // 获取所有商品的分类信息
                    List<Map<String, Object>> categories = productImagesMapper.getProductCategoriesByFarmId(farm.getFarmId());
                    
                    // 按商品ID分组图片
                    Map<Integer, List<ProductImages>> imageMap = productImages.stream()
                        .collect(Collectors.groupingBy(ProductImages::getProductId));
                        
                    // 按商品ID分组分类信息
                    Map<Integer, List<Map<String, Object>>> categoryMap = categories.stream()
                        .collect(Collectors.groupingBy(item -> (Integer)item.get("product_id")));
                    
                    // 构建返回数据
                    for (Products product : farmProducts) {
                        Map<String, Object> productMap = new HashMap<>();
                        productMap.put("product", product);
                        productMap.put("images", imageMap.getOrDefault(product.getProductId(), new ArrayList<>()));
                        productMap.put("categories", categoryMap.getOrDefault(product.getProductId(), new ArrayList<>()));
                        productMap.put("farmName", farm.getFarmName());
                        allProducts.add(productMap);
                    }
                }
            }
            
            return R.success("获取用户商品列表成功", allProducts);
        } catch (Exception e) {
            log.error("获取用户商品列表失败", e);
            return R.error("获取用户商品列表失败：" + e.getMessage());
        }
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public R createProduct(Products product, List<MultipartFile> images, List<Integer> categoryIds) {
        try {
            log.info("开始创建商品: {}, 分类IDs: {}", product.getProductName(), categoryIds);
            
            // 设置创建和更新时间
            Date now = new Date();
            product.setCreatedAt(now);
            product.setUpdatedAt(now);
            
            // 保存商品基本信息
            boolean saved = this.save(product);
            log.info("商品基本信息保存{}, 商品ID: {}", saved ? "成功" : "失败", product.getProductId());
            
            if (!saved) {
                throw new RuntimeException("商品基本信息保存失败");
            }
            
            // 确保获取到商品ID
            if (product.getProductId() == null) {
                throw new RuntimeException("无法获取商品ID");
            }
            
            // 保存商品分类关联
            if (categoryIds != null && !categoryIds.isEmpty()) {
                for (Integer categoryId : categoryIds) {
                    ProductCategories productCategory = new ProductCategories();
                    productCategory.setProductId(product.getProductId());
                    productCategory.setCategoryId(categoryId);
                    productCategoriesMapper.insert(productCategory);
                }
                log.info("商品分类关联保存成功, 商品ID: {}, 分类IDs: {}", product.getProductId(), categoryIds);
            }
            
            log.info("成功获取商品ID: {}", product.getProductId());
            List<ProductImages> productImages = new ArrayList<>();
            
            // 如果有图片，处理图片上传
            if (images != null && !images.isEmpty()) {
                log.info("开始处理商品图片，图片数量: {}, 商品ID: {}", images.size(), product.getProductId());
                
                for (int i = 0; i < images.size(); i++) {
                    MultipartFile file = images.get(i);
                    log.info("处理第{}张图片，原始文件名: {}, 商品ID: {}", i + 1, file.getOriginalFilename(), product.getProductId());
                    
                    // 上传图片到OSS
                    String imageUrl = aliOssUtil.upload(file);
                    log.info("图片上传到OSS成功，URL: {}, 商品ID: {}", imageUrl, product.getProductId());
                    
                    // 创建商品图片记录
                    ProductImages productImage = new ProductImages();
                    productImage.setProductId(product.getProductId());
                    productImage.setImageUrl(imageUrl);
                    productImage.setIsPrimary(i == 0 ? 1 : 0); // 第一张图片设为主图
                    productImage.setCreatedAt(now);
                    
                    // 立即保存每个图片记录
                    try {
                        int insertResult = productImagesMapper.insert(productImage);
                        log.info("商品图片记录保存结果: {}, 商品ID: {}, 图片URL: {}", 
                            insertResult > 0 ? "成功" : "失败",
                            product.getProductId(),
                            imageUrl);
                            
                        if (insertResult <= 0) {
                            throw new RuntimeException("商品图片记录保存失败");
                        }
                        
                        productImages.add(productImage);
                    } catch (Exception e) {
                        log.error("保存商品图片记录失败: 商品ID={}, URL={}, 错误信息={}", 
                            product.getProductId(), imageUrl, e.getMessage());
                        throw new RuntimeException("保存商品图片记录失败: " + e.getMessage());
                    }
                }
                
                log.info("商品图片处理完成，共保存{}张图片，商品ID: {}", productImages.size(), product.getProductId());
            } else {
                log.info("没有上传商品图片，商品ID: {}", product.getProductId());
            }
            
            // 构建返回数据
            Map<String, Object> result = new HashMap<>();
            result.put("product", product);
            result.put("images", productImages);
            result.put("categoryIds", categoryIds);
            
            log.info("商品创建完成: {}, ID: {}", product.getProductName(), product.getProductId());
            return R.success("创建商品成功", result);
        } catch (Exception e) {
            log.error("创建商品失败: {}", e.getMessage(), e);
            throw new RuntimeException("创建商品失败：" + e.getMessage());
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public R deleteProduct(Integer productId) {
        try {
            if (productId == null) {
                return R.error("商品ID不能为空");
            }
            
            log.info("开始删除商品, ID: {}", productId);
            
            // 1. 删除商品图片关联
            LambdaQueryWrapper<ProductImages> imageQuery = new LambdaQueryWrapper<>();
            imageQuery.eq(ProductImages::getProductId, productId);
            productImagesMapper.delete(imageQuery);
            log.info("商品图片关联删除完成");
            
            // 2. 删除商品分类关联
            LambdaQueryWrapper<ProductCategories> categoryQuery = new LambdaQueryWrapper<>();
            categoryQuery.eq(ProductCategories::getProductId, productId);
            productCategoriesMapper.delete(categoryQuery);
            log.info("商品分类关联删除完成");
            
            // 3. 删除商品基本信息
            boolean removed = this.removeById(productId);
            if (!removed) {
                throw new RuntimeException("商品不存在或删除失败");
            }
            log.info("商品基本信息删除完成");
            
            return R.success("删除商品成功");
        } catch (Exception e) {
            log.error("删除商品失败: {}", e.getMessage(), e);
            throw new RuntimeException("删除商品失败：" + e.getMessage());
        }
    }

    @Override
    public R getProductDetail(Integer productId) {
        try {
            if (productId == null) {
                return R.error("商品ID不能为空");
            }
            
            log.info("开始获取商品详情, ID: {}", productId);
            
            // 1. 获取商品基本信息
            Products product = this.getById(productId);
            if (product == null) {
                return R.error("商品不存在");
            }
            
            // 2. 获取商品图片
            LambdaQueryWrapper<ProductImages> imageQuery = new LambdaQueryWrapper<>();
            imageQuery.eq(ProductImages::getProductId, productId);
            List<ProductImages> images = productImagesMapper.selectList(imageQuery);
            
            // 3. 获取商品分类信息
            List<Map<String, Object>> categories = productImagesMapper.getProductCategories(productId);
            
            // 4. 获取农场信息
            Farms farm = farmsMapper.selectById(product.getFarmId());
            
            // 5. 获取农场图片
            if (farm != null) {
                LambdaQueryWrapper<FarmsImages> farmImageQuery = new LambdaQueryWrapper<>();
                farmImageQuery.eq(FarmsImages::getFarmId, farm.getFarmId());
                List<FarmsImages> farmImages = farmsImagesMapper.selectList(farmImageQuery);
                farm.setFarmImages(farmImages);
            }
            
            // 6. 构建返回数据
            Map<String, Object> result = new HashMap<>();
            result.put("product", product);
            result.put("images", images);
            result.put("categories", categories);
            result.put("farm", farm);
            
            log.info("商品详情获取成功, ID: {}", productId);
            return R.success("获取商品详情成功", result);
        } catch (Exception e) {
            log.error("获取商品详情失败: {}", e.getMessage(), e);
            return R.error("获取商品详情失败：" + e.getMessage());
        }
    }

    @Override
    public R updateProductStock(Integer productId, Integer stock) {
        try {
            log.info("开始更新商品库存, productId: {}, stock: {}", productId, stock);
            
            // 检查商品是否存在
            Products product = this.getById(productId);
            if (product == null) {
                log.error("商品不存在, productId: {}", productId);
                return R.error("商品不存在");
            }
            
            // 更新库存
            product.setStock(stock);
            // 更新库存时自动将商品状态改为下架
            product.setStatus(0);
            product.setUpdatedAt(new Date());
            
            boolean updated = this.updateById(product);
            if (updated) {
                log.info("商品库存更新成功, productId: {}, stock: {}", productId, stock);
                return R.success("更新成功");
            } else {
                log.error("商品库存更新失败, productId: {}, stock: {}", productId, stock);
                return R.error("更新失败");
            }
        } catch (Exception e) {
            log.error("更新商品库存时发生错误", e);
            return R.error("更新失败：" + e.getMessage());
        }
    }

    @Override
    public R getAllProducts() {
        try {
            // 1. 获取所有上架商品基本信息
            LambdaQueryWrapper<Products> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Products::getStatus, 1); // 只查询上架的商品
            List<Products> products = this.list(queryWrapper);
            
            if (products.isEmpty()) {
                return R.success("暂无商品数据", new ArrayList<>());
            }

            // 2. 获取所有商品的图片
            List<Integer> productIds = products.stream()
                .map(Products::getProductId)
                .collect(Collectors.toList());

            // 3. 获取所有相关的农场ID
            List<Integer> farmIds = products.stream()
                .map(Products::getFarmId)
                .distinct()
                .collect(Collectors.toList());

            // 4. 批量获取商品图片
            LambdaQueryWrapper<ProductImages> imageQuery = new LambdaQueryWrapper<>();
            imageQuery.in(ProductImages::getProductId, productIds);
            List<ProductImages> allImages = productImagesMapper.selectList(imageQuery);

            // 5. 批量获取农场信息
            List<Farms> farms = farmsMapper.selectBatchIds(farmIds);
            Map<Integer, Farms> farmMap = farms.stream()
                .collect(Collectors.toMap(Farms::getFarmId, farm -> farm));

            // 6. 批量获取农场图片
            LambdaQueryWrapper<FarmsImages> farmImageQuery = new LambdaQueryWrapper<>();
            farmImageQuery.in(FarmsImages::getFarmId, farmIds);
            List<FarmsImages> farmImages = farmsImagesMapper.selectList(farmImageQuery);
            
            // 按农场ID分组图片
            Map<Integer, List<FarmsImages>> farmImageMap = farmImages.stream()
                .collect(Collectors.groupingBy(FarmsImages::getFarmId));

            // 按商品ID分组商品图片
            Map<Integer, List<ProductImages>> productImageMap = allImages.stream()
                .collect(Collectors.groupingBy(ProductImages::getProductId));

            // 7. 获取所有商品的分类信息
            Map<Integer, List<Map<String, Object>>> categoryMap = new HashMap<>();
            for (Integer productId : productIds) {
                List<Map<String, Object>> categories = productImagesMapper.getProductCategories(productId);
                if (categories != null) {
                    categoryMap.put(productId, categories);
                }
            }

            // 8. 构建返回数据
            List<Map<String, Object>> resultList = products.stream().map(product -> {
                Map<String, Object> productMap = new HashMap<>();
                
                // 添加商品基本信息
                productMap.put("product", product);
                
                // 添加商品图片
                productMap.put("images", productImageMap.getOrDefault(product.getProductId(), new ArrayList<>()));
                
                // 添加商品分类
                productMap.put("categories", categoryMap.getOrDefault(product.getProductId(), new ArrayList<>()));
                
                // 添加农场信息
                Farms farm = farmMap.get(product.getFarmId());
                if (farm != null) {
                    Map<String, Object> farmInfo = new HashMap<>();
                    farmInfo.put("farmId", farm.getFarmId());
                    farmInfo.put("farmName", farm.getFarmName());
                    farmInfo.put("description", farm.getFarmDescription());
                    farmInfo.put("address", farm.getFarmAddress());
                    farmInfo.put("images", farmImageMap.getOrDefault(farm.getFarmId(), new ArrayList<>()));
                    productMap.put("farm", farmInfo);
                }

                return productMap;
            }).collect(Collectors.toList());

            log.info("获取商品列表成功，共 {} 条记录", resultList.size());
            return R.success("获取商品列表成功", resultList);
        } catch (Exception e) {
            log.error("获取商品列表失败: {}", e.getMessage(), e);
            return R.error("获取商品列表失败：" + e.getMessage());
        }
    }

    @Override
    public R searchProducts(String keyword) {
        try {
            if (keyword == null || keyword.trim().isEmpty()) {
                return R.error("搜索关键词不能为空");
            }

            // 构建查询条件
            LambdaQueryWrapper<Products> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Products::getStatus, 1) // 只查询上架的商品
                      .like(Products::getProductName, keyword)
                    .or()
                    .like(Products::getProductDescription, keyword);

            // 获取商品列表
            List<Products> products = this.list(queryWrapper);
            if (products.isEmpty()) {
                return R.success("未找到相关商品", new ArrayList<>());
            }

            // 获取商品ID列表
            List<Integer> productIds = products.stream()
                    .map(Products::getProductId)
                    .collect(Collectors.toList());

            // 获取农场ID列表
            List<Integer> farmIds = products.stream()
                    .map(Products::getFarmId)
                    .distinct()
                    .collect(Collectors.toList());

            // 获取商品图片
            LambdaQueryWrapper<ProductImages> imageQuery = new LambdaQueryWrapper<>();
            imageQuery.in(ProductImages::getProductId, productIds);
            List<ProductImages> allImages = productImagesMapper.selectList(imageQuery);

            // 获取农场信息
            Map<Integer, Farms> farmMap = farmsMapper.selectBatchIds(farmIds)
                    .stream()
                    .collect(Collectors.toMap(Farms::getFarmId, farm -> farm));

            // 按商品ID分组图片
            Map<Integer, List<ProductImages>> imageMap = allImages.stream()
                    .collect(Collectors.groupingBy(ProductImages::getProductId));

            // 构建返回数据
            List<Map<String, Object>> resultList = products.stream().map(product -> {
                Map<String, Object> productMap = new HashMap<>();
                productMap.put("product", product);
                productMap.put("images", imageMap.getOrDefault(product.getProductId(), new ArrayList<>()));
                productMap.put("farm", farmMap.get(product.getFarmId()));
                return productMap;
            }).collect(Collectors.toList());

            return R.success("搜索成功", resultList);
        } catch (Exception e) {
            log.error("搜索商品失败", e);
            return R.error("搜索商品失败：" + e.getMessage());
        }
    }

    @Override
    public R getProductsByCategory(Integer categoryId) {
        try {
            if (categoryId == null) {
                return R.error("分类ID不能为空");
            }

            // 通过分类ID获取商品ID列表
            LambdaQueryWrapper<ProductCategories> categoryQuery = new LambdaQueryWrapper<>();
            categoryQuery.eq(ProductCategories::getCategoryId, categoryId);
            List<ProductCategories> productCategories = productCategoriesMapper.selectList(categoryQuery);

            if (productCategories.isEmpty()) {
                return R.success("该分类下暂无商品", new ArrayList<>());
            }

            // 获取商品ID列表
            List<Integer> productIds = productCategories.stream()
                    .map(ProductCategories::getProductId)
                    .collect(Collectors.toList());

            // 获取商品信息（只获取上架的商品）
            LambdaQueryWrapper<Products> productQuery = new LambdaQueryWrapper<>();
            productQuery.in(Products::getProductId, productIds)
                      .eq(Products::getStatus, 1); // 只查询上架的商品
            List<Products> products = this.list(productQuery);

            if (products.isEmpty()) {
                return R.success("该分类下暂无上架商品", new ArrayList<>());
            }

            // 获取农场ID列表
            List<Integer> farmIds = products.stream()
                    .map(Products::getFarmId)
                    .distinct()
                    .collect(Collectors.toList());

            // 获取商品图片
            LambdaQueryWrapper<ProductImages> imageQuery = new LambdaQueryWrapper<>();
            imageQuery.in(ProductImages::getProductId, productIds);
            List<ProductImages> allImages = productImagesMapper.selectList(imageQuery);

            // 获取农场信息
            Map<Integer, Farms> farmMap = farmsMapper.selectBatchIds(farmIds)
                    .stream()
                    .collect(Collectors.toMap(Farms::getFarmId, farm -> farm));

            // 按商品ID分组图片
            Map<Integer, List<ProductImages>> imageMap = allImages.stream()
                    .collect(Collectors.groupingBy(ProductImages::getProductId));

            // 构建返回数据
            List<Map<String, Object>> resultList = products.stream().map(product -> {
                Map<String, Object> productMap = new HashMap<>();
                productMap.put("product", product);
                productMap.put("images", imageMap.getOrDefault(product.getProductId(), new ArrayList<>()));
                productMap.put("farm", farmMap.get(product.getFarmId()));
                return productMap;
            }).collect(Collectors.toList());

            return R.success("获取分类商品成功", resultList);
        } catch (Exception e) {
            log.error("获取分类商品失败", e);
            return R.error("获取分类商品失败：" + e.getMessage());
        }
    }

    @Override
    public R updateProductStatus(Integer productId, Integer status) {
        try {
            if (productId == null || status == null) {
                return R.error("商品ID和状态不能为空");
            }
            
            Products product = this.getById(productId);
            if (product == null) {
                return R.error("商品不存在");
            }
            
            product.setStatus(status);
            product.setUpdatedAt(new Date());
            
            boolean success = this.updateById(product);
            if (success) {
                return R.success("更新商品状态成功");
            } else {
                return R.error("更新商品状态失败");
            }
        } catch (Exception e) {
            log.error("更新商品状态失败", e);
            return R.error("更新商品状态失败：" + e.getMessage());
        }
    }

    @Override
    public R getAllProductsForAdmin() {
        try {
            log.info("获取所有商品列表（管理员）");
            
            // 查询所有商品，不限制状态
            List<Products> products = this.list();
            
            if (products.isEmpty()) {
                return R.success("获取成功", new ArrayList<>());
            }
            
            // 获取农场ID列表
            List<Integer> farmIds = products.stream()
                    .map(Products::getFarmId)
                    .distinct()
                    .collect(Collectors.toList());
                    
            // 获取商品ID列表
            List<Integer> productIds = products.stream()
                    .map(Products::getProductId)
                    .collect(Collectors.toList());

            // 获取商品主图
            LambdaQueryWrapper<ProductImages> imageQuery = new LambdaQueryWrapper<>();
            imageQuery.in(ProductImages::getProductId, productIds)
                    .eq(ProductImages::getIsPrimary, 1);
            List<ProductImages> productImages = productImagesMapper.selectList(imageQuery);

            // 获取农场信息
            Map<Integer, Farms> farmMap = farmsMapper.selectBatchIds(farmIds)
                    .stream()
                    .collect(Collectors.toMap(Farms::getFarmId, farm -> farm));

            // 按商品ID分组图片
            Map<Integer, String> imageMap = productImages.stream()
                    .collect(Collectors.toMap(
                            ProductImages::getProductId,
                            ProductImages::getImageUrl,
                            (existing, replacement) -> existing
                    ));

            // 构建返回数据
            List<Map<String, Object>> result = new ArrayList<>();
            for (Products product : products) {
                Map<String, Object> item = new HashMap<>();
                Farms farm = farmMap.get(product.getFarmId());
                
                item.put("productId", product.getProductId());
                item.put("farmId", product.getFarmId());
                item.put("productName", product.getProductName());
                item.put("productDescription", product.getProductDescription());
                item.put("productImage", imageMap.getOrDefault(product.getProductId(), ""));
                item.put("farmName", farm != null ? farm.getFarmName() : "未知农场");
                item.put("price", product.getPrice());
                item.put("stock", product.getStock());
                item.put("status", product.getStatus());
                item.put("createdAt", product.getCreatedAt());
                item.put("updatedAt", product.getUpdatedAt());
                
                result.add(item);
            }

            log.info("获取所有商品列表成功，共 {} 条记录", result.size());
            return R.success("获取成功", result);
        } catch (Exception e) {
            log.error("获取所有商品列表失败: {}", e.getMessage(), e);
            return R.error("获取所有商品列表失败：" + e.getMessage());
        }
    }
    
    public R getLatestProducts() {
        try {
            // 1. 获取最新的上架商品基本信息
            LambdaQueryWrapper<Products> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Products::getStatus, 1) // 只查询上架的商品
                      .orderByDesc(Products::getCreatedAt)
                      .last("LIMIT 10");
            List<Products> products = this.list(queryWrapper);
            
            if (products.isEmpty()) {
                return R.success("暂无商品数据", new ArrayList<>());
            }

            // 2. 获取所有商品的图片
            List<Integer> productIds = products.stream()
                .map(Products::getProductId)
                .collect(Collectors.toList());

            // 3. 获取所有相关的农场ID
            List<Integer> farmIds = products.stream()
                .map(Products::getFarmId)
                .distinct()
                .collect(Collectors.toList());

            // 4. 批量获取商品图片
            LambdaQueryWrapper<ProductImages> imageQuery = new LambdaQueryWrapper<>();
            imageQuery.in(ProductImages::getProductId, productIds);
            List<ProductImages> allImages = productImagesMapper.selectList(imageQuery);

            // 5. 批量获取农场信息
            List<Farms> farms = farmsMapper.selectBatchIds(farmIds);
            Map<Integer, Farms> farmMap = farms.stream()
                .collect(Collectors.toMap(Farms::getFarmId, farm -> farm));

            // 6. 批量获取农场图片
            LambdaQueryWrapper<FarmsImages> farmImageQuery = new LambdaQueryWrapper<>();
            farmImageQuery.in(FarmsImages::getFarmId, farmIds);
            List<FarmsImages> farmImages = farmsImagesMapper.selectList(farmImageQuery);
            
            // 按农场ID分组图片
            Map<Integer, List<FarmsImages>> farmImageMap = farmImages.stream()
                .collect(Collectors.groupingBy(FarmsImages::getFarmId));

            // 按商品ID分组商品图片
            Map<Integer, List<ProductImages>> productImageMap = allImages.stream()
                .collect(Collectors.groupingBy(ProductImages::getProductId));

            // 7. 获取所有商品的分类信息
            Map<Integer, List<Map<String, Object>>> categoryMap = new HashMap<>();
            for (Integer productId : productIds) {
                List<Map<String, Object>> categories = productImagesMapper.getProductCategories(productId);
                if (categories != null) {
                    categoryMap.put(productId, categories);
                }
            }

            // 8. 构建返回数据
            List<Map<String, Object>> resultList = products.stream().map(product -> {
                Map<String, Object> productMap = new HashMap<>();
                
                // 添加商品基本信息
                productMap.put("product", product);
                
                // 添加商品图片
                productMap.put("images", productImageMap.getOrDefault(product.getProductId(), new ArrayList<>()));
                
                // 添加商品分类
                productMap.put("categories", categoryMap.getOrDefault(product.getProductId(), new ArrayList<>()));
                
                // 添加农场信息
                Farms farm = farmMap.get(product.getFarmId());
                if (farm != null) {
                    Map<String, Object> farmInfo = new HashMap<>();
                    farmInfo.put("farmId", farm.getFarmId());
                    farmInfo.put("farmName", farm.getFarmName());
                    farmInfo.put("description", farm.getFarmDescription());
                    farmInfo.put("address", farm.getFarmAddress());
                    farmInfo.put("images", farmImageMap.getOrDefault(farm.getFarmId(), new ArrayList<>()));
                    productMap.put("farm", farmInfo);
                }

                return productMap;
            }).collect(Collectors.toList());

            log.info("获取最新商品列表成功，共 {} 条记录", resultList.size());
            return R.success("获取最新商品列表成功", resultList);
        } catch (Exception e) {
            log.error("获取最新商品列表失败: {}", e.getMessage(), e);
            return R.error("获取最新商品列表失败：" + e.getMessage());
        }
    }
}




